/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable react/jsx-key */
import DictTag from "@/components/DictTag";
import { ClearOutlined, DeleteOutlined, ExclamationCircleOutlined, PlusOutlined } from "@ant-design/icons";
import { Column, Pie } from "@ant-design/plots";
import { ActionType, ProCard, ProColumns, ProTable } from "@ant-design/pro-components";
import type { FormInstance, MenuProps } from "antd";
import { Button, Col, Dropdown, Modal, Row, message } from "antd";
import React, { useEffect, useRef, useState } from "react";
import CountPie from "./components/countPie";
import LogDetails from "./components/logDetails";
import WeekColumn from "./components/weekColumn";
import { countData, getPageList } from "@/services/api/module/system/operLog";
import { getDict } from "@/services/api/module/system/dict";
import CustomerTable from "@/components/CustomerTable";
import { useTableScroll } from "@/hooks/useTableScroll";
import { createTableColumns, pagination, tableStyle, tableTab } from "./constants";
import ErrorLog from "./components/ErrorLog";
import { dict } from "@/utils/DictionaryCacheManager";

const OperlogTableList: React.FC = () => {
	const formTableRef = useRef<FormInstance>();
	const [errorOpen, setErrorOpen] = useState<boolean>(false);
	const [activeKey, setActiveKey] = useState<React.Key>("oper");
	const [modalVisible, setModalVisible] = useState<boolean>(false);
	const actionRef = useRef<ActionType>();
	const [currentRow, setCurrentRow] = useState<API.Setting.OperlogVo>();
	const [selectedRows, setSelectedRows] = useState<API.Setting.OperlogVo[]>([]);
	const [businessTypeOptions, setBusinessTypeOptions] = useState<any>([]);
	const [operatorTypeOptions, setOperatorTypeOptions] = useState<any>([]);
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [params, setParams] = useState<any>({ type: activeKey === "oper" ? 0 : 1 });
	const [pieData, setPieData] = useState<any>([]);
	const tableSrcollHeight = useTableScroll({ extraHeight: 515 });
	const [statusData, setStatusData] = useState<any>([]);
	useEffect(() => {
		dict.getDict("sys_common_status", true).then(data => {
			setStatusOptions(data);
		});
		dict.getDict("sys_oper_type", true).then(data => {
			setBusinessTypeOptions(data);
		});
		dict.getDict("sys_operator_type", true).then(data => {
			setOperatorTypeOptions(data);
		});
	}, []);

	useEffect(() => {
		countData().then((data: any) => {
			const pie = data?.pie;
			const columns = data?.column;
			const newColumns: any[] = [];
			columns?.forEach((column: { status: string; name: any }) => {
				if (column?.status === "0") {
					column.name = "操作成功";
				} else {
					column.name = "操作失败";
				}
				// return column;
				newColumns.push(column);
			});
			const pieData = [
				{
					fieldName: "操作成功",
					value: Number(pie.success)
				},
				{
					fieldName: "操作失败",
					value: Number(pie.error)
				}
			];
			setStatusData(newColumns);
			setPieData(pieData);
		});
	}, []);

	const handleColumnDetails = (record: API.Setting.OperlogVo) => {
		setModalVisible(true);
		setCurrentRow(record);
	};
	const handleColumnLog = (record: API.Setting.OperlogVo) => {
		// setModalVisible(true);
		// setCurrentRow(record);
		setErrorOpen(true);
		setCurrentRow(record);
	};
	const columns = createTableColumns(businessTypeOptions, operatorTypeOptions, handleColumnDetails, handleColumnLog);
	//数据请求
	const tableDataRequest = async (params: {} | undefined) => {
		return await getPageList(params).then((data: any) => {
			return data;
		});
	};
	const items: MenuProps["items"] = [
		{
			key: "oneMonth",
			label: <a onClick={() => {}}>近一个月</a>
		},
		{
			key: "twoMonth",
			label: <a onClick={() => {}}>近三个月</a>
		},
		{
			type: "divider"
		},
		{
			key: "all",
			label: <a>清理全部</a>
		}
	];
	return (
		<>
			<Row gutter={[12, 10]}>
				<Col span="16">
					<ProCard>{statusData.length > 0 ? <WeekColumn data={statusData} /> : "loading..."}</ProCard>
				</Col>
				<Col span="8">
					<ProCard>{pieData.length > 0 ? <CountPie data={pieData} /> : "loading..."}</ProCard>
				</Col>
				<Col span="24">
					<ProTable<API.Setting.OperlogVo>
						actionRef={actionRef}
						scroll={{ y: tableSrcollHeight, x: 1000 }}
						search={false}
						params={params}
						tableStyle={tableStyle}
						toolbar={{
							search: {
								allowClear: true,
								style: { width: "250px" },
								onSearch: (value: string) => {
									setParams({ ...params, title: value });
									actionRef.current?.reload();
								}
							},
							menu: {
								type: "tab",
								activeKey: activeKey,
								items: tableTab,
								onChange: key => {
									setParams({ status: key === "oper" ? "0" : "1" });
									setActiveKey(key as string);
								}
							}
						}}
						formRef={formTableRef}
						rowKey="id"
						key="operlogList"
						pagination={pagination}
						// @ts-ignore
						toolBarRender={
							() => {
								return (
									<Dropdown menu={{ items }} placement="bottom">
										<Button icon={<ClearOutlined />}>清理日志</Button>
									</Dropdown>
								);
							}
							// <Button
							// 	type="primary"
							// 	key="remove"
							// 	danger
							// 	onClick={async () => {
							// 		Modal.confirm({
							// 			title: "是否确认清空所有操作日志?",
							// 			icon: <ExclamationCircleOutlined />,
							// 			content: "该操作是不可逆的，请谨慎操作",
							// 			async onOk() {
							// 				return new Promise<void>((resolve, reject) => {
							// 					// setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
							// 					clearOperLog()
							// 						.then((res: any) => {
							// 							// todo 需要把图表的数据刷新
							// 							message.success(res.msg);
							// 							actionRef?.current?.reload();
							// 							resolve();
							// 						})
							// 						.catch(() => {
							// 							reject();
							// 						});
							// 				});
							// 			},
							// 			onCancel() {}
							// 		});
							// 	}}
							// >
							// 	<DeleteOutlined />
							// 	清空
							// </Button>,
						}
						request={tableDataRequest}
						columns={columns}
					/>
				</Col>
			</Row>
			<LogDetails
				businessTypeOptions={businessTypeOptions}
				operatorTypeOptions={operatorTypeOptions}
				statusOptions={statusOptions}
				open={modalVisible}
				value={currentRow}
				onCancel={() => {
					setModalVisible(false);
					setCurrentRow(undefined);
				}}
			/>
			<ErrorLog
				open={errorOpen}
				value={currentRow}
				onCancel={() => {
					setErrorOpen(false);
					setCurrentRow(undefined);
				}}
			/>
		</>
	);
};
export default OperlogTableList;
